//调整价格
import React, { useEffect, useState } from 'react';
import { Form, message, InputNumber, Divider, Radio } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { updateAmount } from '../service';
import { getCurrentUser } from '@/utils/authority';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import styles from './index.module.less';

const layout1 = {
  //发布表单排布
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const ChangePriceModal = ({ visible, itemData, handleOk, handleCancel }) => {

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
	const [currentAmount, setCAmount] = useState();
	const [purchaseAmount, setPAmount] = useState();
 
  useEffect(() => {
    if (visible) {
      form.resetFields();
			setCAmount(itemData.deductionBalance);
			setPAmount(itemData.purchaseDeductionBalance);
    }
  }, [visible]);

  //校验
  const onOk = () => {
    form.validateFields().then((val) => {
      sendData(val);
    });
  };

  const sendData = async (val) => {
		const changeCAmount = currentAmount - itemData.deductionBalance;
		const changePAmount = purchaseAmount - itemData.purchaseDeductionBalance;
		if(changeCAmount == 0 && changePAmount == 0) {
			message.info('检测到调整金额未发生变更，本次提交不生效');
			return;
		}
    setLoading(true);
    const { success, msg } = await updateAmount({
      id: itemData.id,
      currentAmount: changeCAmount || undefined,
      purchaseCurrentAmount: changePAmount || undefined,
			storeId: itemData.storeId,
			shortName: itemData.userName,
			uuid: getCurrentUser().uuid,
    });
    if (success) {
      message.success(msg);
      handleOk();
    }
    setLoading(false);
  };

  const onCancel = () => {
    handleCancel();
    form.resetFields();
  };

	//计算变更后的拿货金额-变更调整方式
	const changeCAmountType = e => {
		const cAmountType = e.target.value;
		const cAmount = form.getFieldValue('cAmount');
		const amount = Number(itemData.deductionBalance);
		if(cAmount) {
			//金额扣减最大值不能超过可抵扣金额
			if(cAmountType == 2 && cAmount > amount) {
				form.resetFields(['cAmount']);
				setCAmount(itemData.deductionBalance);
				return;
			}
			const changeAmount = Number(Number(cAmount).toFixed(2));
			const newAmount = cAmountType == 1 ? amount + changeAmount : Number((amount - changeAmount).toFixed(2));
			setCAmount(newAmount);
		} 
	}

	//计算变更后的拿货金额-变更调整金额
	const changeCAmount = e => {
		const cAmount = e.target.value;
		if(isNaN(cAmount) || cAmount < 0) {
			return;
		}
		const cAmountType = form.getFieldValue('cAmountType');
		const amount = Number(itemData.deductionBalance);
		if(cAmountType) {
			if(cAmountType == 2 && cAmount > amount) {
				form.resetFields(['cAmount']);
				setCAmount(itemData.deductionBalance);
				return;
			} 
			const changeAmount = Number(Number(cAmount).toFixed(2));
			const newAmount = cAmountType == 1 ? amount + changeAmount : Number((amount - changeAmount).toFixed(2));
			setCAmount(newAmount);
		}
	}

		//计算变更后的采购金额-变更调整方式
		const changePAmountType = e => {
			const pAmountType = e.target.value;
			const pAmount = form.getFieldValue('pAmount');
			const amount = Number(itemData.purchaseDeductionBalance);
			if(pAmount) {
				//金额扣减最大值不能超过可抵扣金额
				if(pAmountType == 2 && pAmount > amount) {
					form.resetFields(['pAmount']);
					setPAmount(itemData.purchaseDeductionBalance);
					return;
				}
				const changeAmount = Number(Number(pAmount).toFixed(2));
				const newAmount = pAmountType == 1 ? amount + changeAmount : Number((amount - changeAmount).toFixed(2));
				setPAmount(newAmount);
			} 
		}
	
		//计算变更后的采购金额-变更调整金额
		const changePAmount = e => {
			const pAmount = e.target.value;
			if(isNaN(pAmount) || pAmount < 0) {
				return;
			}
			const pAmountType = form.getFieldValue('pAmountType');
			const amount = Number(itemData.purchaseDeductionBalance);
			if(pAmountType) {
				if(pAmountType == 2 && pAmount > amount) {
					form.resetFields(['pAmount']);
					setPAmount(itemData.purchaseDeductionBalance);
					return;
				} 
				const changeAmount = Number(Number(pAmount).toFixed(2));
				const newAmount = pAmountType == 1 ? amount + changeAmount : Number((amount - changeAmount).toFixed(2));
				setPAmount(newAmount);
			}
		}

  return (
    <CommonModal
      title="调整价格"
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form
        {...layout1}
        form={form}
        name="change-price-modal-form"
      >
        <Form.Item
          name="cAmountType"
          label={<><span className={styles.textIcon}>拿</span>抵扣金额变动</>}
        >
					<Radio.Group onChange={changeCAmountType}>
						<Radio value={1}>金额增加<PlusOutlined style={{ color: 'red', marginLeft: '4px' }} /></Radio>
						<Radio value={2}>金额减少<MinusOutlined  style={{ color: 'green', marginLeft: '4px' }} /></Radio>
					</Radio.Group>
        </Form.Item>
				<Form.Item
          name="cAmount"
          label=" "
					extra={`变更后金额为${currentAmount}元`}
					colon={false}
        >
          <InputNumber precision={2} onBlur={changeCAmount} addonAfter="元" min={0} />
        </Form.Item>
				<Divider style={{ margin: '8px 0'}} />
				<Form.Item
          name="pAmountType"
          label={<><span className={styles.textIcon}>采</span>抵扣金额变动</>}
        >
					<Radio.Group onChange={changePAmountType}>
						<Radio value={1}>金额增加<PlusOutlined style={{ color: 'red', marginLeft: '4px' }} /></Radio>
						<Radio value={2}>金额减少<MinusOutlined  style={{ color: 'green', marginLeft: '4px' }} /></Radio>
					</Radio.Group>
        </Form.Item>
        <Form.Item
          name="pAmount"
					label=" "
					colon={false}
					extra={`变更后金额为${purchaseAmount}元`}
        >
          <InputNumber precision={2} onBlur={changePAmount} addonAfter="元" min={0} />
        </Form.Item>
      </Form>
			<Divider style={{ margin: '8px 0'}} />
      <div style={{ marginLeft: '45px' }} className="common-color9">
        <p>注：</p>
        <p>1、这里改动价格是在原有的基础上进行价格变更</p>
        <p>2、金额变动之前建议与商户之间进行沟通确认后再更改调整。</p>
      </div>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default ChangePriceModal;
